package edu.jptest.serviceImp;

import java.util.ArrayList;
import java.util.List;

import edu.jptest.bean.Examine;
import edu.jptest.bean.ExamineQuestionType;
import edu.jptest.bean.Favorite;
import edu.jptest.bean.Question;
import edu.jptest.dao.AnswerDAO;
import edu.jptest.dao.ExamineDAO;
import edu.jptest.dao.ExamineQuestionTypeDAO;
import edu.jptest.dao.FavoriteDAO;
import edu.jptest.dao.QuestionDAO;
import edu.jptest.service.IExamineService;

public class ExamineService implements IExamineService {

	// 判断试题正确性
	public boolean gradeExaminePaper(String answer, int questionId) {
		QuestionDAO questionDAO = new QuestionDAO();
		AnswerDAO answerDAO = new AnswerDAO();
		Question question = questionDAO.getQuestionByQuestionId(questionId);
		// 获得该问题的答案
		// 问题被做次数加一
		question.setDoTimes(question.getDoTimes() + 1);
		// 判断答案正确性
		if (answer.equals(answerDAO.getAnswerByAnswerId(question.getAnswerId())
				.getAnswer())) {
			// 答案正确，问题的正确次数加一
			question.setRightCounts(question.getRightCounts() + 1);
			questionDAO.updateQuestion(question);
			return true;
		} else {
			questionDAO.updateQuestion(question);
			return false;
		}
	}

	// 得到每个大题的分数
	public List<Float> getGrades(List<List<Integer>> examinPaper,
			int examinePaperId, List<List<String>> answer) {
		// 各个大题的分数集合
		List<Float> grades = new ArrayList<Float>();
		// 每个大题中各个小题的分值
		float avgGrade;
		ExamineQuestionTypeDAO examineQuestionTypeDAO = new ExamineQuestionTypeDAO();
		List<Integer> examPaperQuesTypeIds = examineQuestionTypeDAO
				.getExamineQuestionSubjectIdByExaminePaperId(examinePaperId);
		ExamineQuestionType examineQuestionType;
		for (int i = 0; i < examinPaper.size(); i++) {
			// 顺序获得试卷中的相应卷题型
			examineQuestionType = examineQuestionTypeDAO
					.getExamineQuestionTypeByExamineQuestionTypeId(examPaperQuesTypeIds
							.get(i));
			// 每个大题的分数
			float grade = 0;
			for (int j = 0; j < examinPaper.get(i).size(); j++) {
				avgGrade = examineQuestionType.getTypeScore()
						/ examineQuestionType.getQuestionTypeSum();
				if (gradeExaminePaper(answer.get(i).get(j), examinPaper.get(i)
						.get(j))) {
					grade += avgGrade;
				}
			}
			// 将每个大题的分值分别添加到分值集合中
			grades.add(grade);
		}
		return grades;
	}

	// 得到试卷总分数
	public float getGrade(List<Float> grades) {
		float grade = 0;
		for (int i = 0; i < grades.size(); i++) {
			grade += grades.get(i);
		}
		return grade;
	}

	// 插入考务
	public void insertExamine(Examine examine) {
		ExamineDAO examineDAO = new ExamineDAO();
		examineDAO.insertExamine(examine);
	}

	// 将试题加入收藏夹
	public void insertFavorite(Favorite favorite) {
		FavoriteDAO favoriteDAO = new FavoriteDAO();
		favoriteDAO.insertFavorite(favorite);
	}
}
